package com.xw.convert;


/**
 * 用户可以直接调用类里面的两个静态方法
 * @author gxw
 *
 */
public class CRC16 {
	
	//CRC校验。
	  public static int CRC_XModem(byte[] bytes,int initValue){ 
	       int crc =initValue;          // initial value  
	       int polynomial = 0x1021;   
	       for (int index = 0 ; index< bytes.length; index++) { 
	           byte b = bytes[index]; 
	           for (int i = 0; i < 8; i++) { 
	               boolean bit = ((b   >> (7-i) & 1) == 1); 
	               boolean c15 = ((crc >> 15    & 1) == 1); 
	               crc <<= 1; 
	               if (c15 ^ bit) crc ^= polynomial; 
	            } 
	       } 
	       crc &= 0xffff; 
	       return crc;    
	} 
	
	/**
	 * 得出CRC计算结果
	 * @param buf 要计算CRC的字符串
	 * @return 整数
	 */
	public static int getCRC(String buf) {
		int crc = 0xFFFF; // initial value
		int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)

		for (int j = 0; j < buf.length(); j++) {
			char b = buf.charAt(j);
			for (int i = 0; i < 8; i++) {
				boolean bit = ((b >> (7 - i) & 1) == 1);
				boolean c15 = ((crc >> 15 & 1) == 1);
				crc <<= 1;
				if (c15 ^ bit)
					crc ^= polynomial;
			}
		}

		crc &= 0xffff;
		return crc;
	}

	/**
	 * 得出CRC计算结果
	 * @param buf 要计算CRC的字符串
	 * @return 字符串,2个字节
	 */
	public static String getCRCString(String buf) {
		int crc = 0xFFFF; // initial value
		int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12)

		for (int j = 0; j < buf.length(); j++) {
			char b = buf.charAt(j);
			for (int i = 0; i < 8; i++) {
				boolean bit = ((b >> (7 - i) & 1) == 1);
				boolean c15 = ((crc >> 15 & 1) == 1);
				crc <<= 1;
				if (c15 ^ bit)
					crc ^= polynomial;
			}
		}

		crc &= 0xffff;
		String str = "" + (char) (crc / 256) + (char) (crc % 256);
		return str;
	}

//	public static void main(String[] args) {
//		// 得出CRC计算结果(数字)
//		System.out.println(CRC16.getCRC("hello"));
//		// 得出CRC计算结果(字符串，2个字节)
//		System.out.println(CRC16.getCRCString("hello"));
//	}
}
